<?php
class Region extends Doctrine_Record {
    public function setTableDefinition() {
        $this->setTableName('region');
        $this->hasColumn('modificado','integer'); //sirve para trabajar con la cabecera HTTP_IF_MODIFIED_SINCE
        $this->hasColumn('contenido','string',255);
    }

    public function setUp(){
        $this->hasMany('Provincia as provincias',array(
            'local'=>'id',
            'foreign'=>'id_region'
        ));
    }

    //INCIO DE GETERS Y SETERS
   public function getContenido () {
        return utf8_decode($this->_get('contenido'));
    }
    public function setContenido ($contenido) {
        $this->_set('contenido', utf8_encode($contenido));
    }
    public function getProvincias () {
        $q = Doctrine_Query::create()
            ->select('d.*')
            ->from('provincia d')
            ->innerJoin('d.region p')
            ->where('p.id = '.$this->id)
            ->orderBy('d.contenido');
        return $q->execute();
    }
    public function getComunas () {
        $q = Doctrine_Query::create()
            ->select('l.*')
            ->from('comuna l')
            ->where('l.id_provincia in ()')
            ->where('l.id_provincia IN (SELECT u.id FROM provincia u INNER JOIN u.region p WHERE p.id = ?)', $this->id)
            ->orderBy('l.contenido');
        return $q->execute();
    }
    //FIN SETERS Y GETERS
    
    public static function listar () {
        $q = Doctrine_Query::create()
            ->select('p.*')
            ->from('region p')
            ->where('p.id <> 0')
            ->orderBy('p.contenido');
        return $q->execute();
    }
    
    public static function toSelect ($objeto=false) {
        $html = '<select id="selectRegion" name="region">';
        $regiones = self::listar();
        $html .= '<option selected="selected" value="">Elegir</option>';
        $idRegion = ($objeto)?$objeto->comuna->provincia->region->id:0;
        foreach ($regiones as $prov) {
            $selected = ($prov->id == $idRegion)?'  selected="selected"':'';
            $html .= '<option value="'.$prov->id.'"'.$selected.'>'.$prov->contenido.'</option>';
        }
        $html .= '</select>';
        return $html;
    }
}
?>